package com.zhehekeji.opsys.api.service.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhehekeji.opsys.api.code.ZoneManagerResultCode;
import com.zhehekeji.opsys.api.common.util.DateFormatUtil;
import com.zhehekeji.opsys.api.conf.Config;
import com.zhehekeji.opsys.api.entity.TCmsCategory;
import com.zhehekeji.opsys.api.entity.TCmsProgram;
import com.zhehekeji.opsys.api.entity.TCmsSeries;
import com.zhehekeji.opsys.api.entity.TZone;
import com.zhehekeji.opsys.api.entity.TZoneCollect;
import com.zhehekeji.opsys.api.entity.TZonePlay;
import com.zhehekeji.opsys.api.req.AddCollectReq;
import com.zhehekeji.opsys.api.req.AddPlayRecordReq;
import com.zhehekeji.opsys.api.resp.AddZoneCollectResp;
import com.zhehekeji.opsys.api.resp.AddZonePlayRecordResp;
import com.zhehekeji.opsys.api.resp.GetZoneCollectListResp;
import com.zhehekeji.opsys.api.resp.GetZoneCollectResp;
import com.zhehekeji.opsys.api.resp.GetZonePlayRecordListResp;
import com.zhehekeji.opsys.api.resp.GetZonePlayRecordResp;
import com.zhehekeji.opsys.api.resp.RemoveZoneCollectResp;
import com.zhehekeji.opsys.api.resp.RemoveZonePlayRecordResp;
import com.zhehekeji.opsys.api.service.CommonService;

/**
 * @ClassName ZoneManagerService
 * @Description TODO
 * @date 2016-7-20   上午9:38:50
 */
@Service
public class ZoneManagerService extends CommonService {

    private final static Logger logger = LoggerFactory.getLogger(ZoneManagerService.class);

    @Autowired
    private Config config;

    @Transactional
    public AddZoneCollectResp addCollect(AddCollectReq addCollectReq) {
        AddZoneCollectResp resp = new AddZoneCollectResp();
        String resultDesc = "用户新增专区收藏";
        try {
            if (addCollectReq == null) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            String zoneCode = addCollectReq.getZoneCode();
            String userID = addCollectReq.getUserID();
            String programCode = addCollectReq.getProgramCode();
            String programName = addCollectReq.getProgramName();
            int seriesFlag = addCollectReq.getSeriesFlag();
            String seriesCode = addCollectReq.getSeriesCode();
            String categoryCode = addCollectReq.getCategoryCode();
            String poster = addCollectReq.getPoster();
            resultDesc = String.format("用户[%s]新增专区[%s]收藏[%s|%s]类型[%s]", userID, zoneCode, programCode, programName, seriesFlag);

            if (StringUtils.isEmpty(StringUtils.trim(zoneCode)) || StringUtils.isEmpty(StringUtils.trim(userID))
                    || StringUtils.isEmpty(StringUtils.trim(programCode)) || StringUtils.isEmpty(StringUtils.trim(programName))) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            if (seriesFlag != 0 && seriesFlag != 1) {
                resultDesc = resultDesc + "失败，类型非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }

            TZone tmpTZone = entityDao.get(TZone.class, "o.code=?1", new Object[]{zoneCode});
            if (tmpTZone == null) {
                resultDesc = resultDesc + "失败，专区code["+zoneCode+"]不存在，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            if (tmpTZone.getStatus() == 0) {
                resultDesc = resultDesc + "失败，专区code=["+zoneCode+"]已停用status=["+tmpTZone.getStatus()+"]！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.ZONEHAS_BEEN_STOPPED);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            int tmpCollectLimit = tmpTZone.getCollectLimit() == null ? 0 : tmpTZone.getCollectLimit();
            if (tmpCollectLimit <= 0) {
                resultDesc = resultDesc + "失败，数据库数据错误！收藏限制数量["+tmpTZone.getCollectLimit()+"]";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.DATABASE_EXCEPTION);
                resp.setResultDesc(resultDesc);
                return resp;
            }

            TZoneCollect tmpTZoneCollect = entityDao.get(TZoneCollect.class, "o.tzone.code=?1 and o.userId=?2 and o.programCode=?3",
                    new Object[]{zoneCode, userID, programCode});
            if (tmpTZoneCollect != null) {
                tmpTZoneCollect.setCpCode(tmpTZone.getCpCode());
                tmpTZoneCollect.setProgramName(programName);
                tmpTZoneCollect.setRecordTime(new Date());
                tmpTZoneCollect.setSeriesFlag(seriesFlag);
                tmpTZoneCollect.setSeriesCode(seriesCode);
                tmpTZoneCollect.setPosterUrl(poster);
                if (seriesFlag == 1) {
                    TCmsSeries tcmsSeries = entityDao.get(TCmsSeries.class, "o.code=?1", new Object[]{seriesCode});
                    if (null != tcmsSeries) {
                        tmpTZoneCollect.setStillImg(tcmsSeries.getStillUrl());
                    }
                } else if (seriesFlag == 0) {
                    TCmsProgram tmpTProgram = entityDao.get(TCmsProgram.class, "o.code=?1", new Object[]{programCode});
                    if (null != tmpTProgram) {
                        tmpTZoneCollect.setStillImg(tmpTProgram.getStillUrl());
                    }
                }
                TCmsCategory category = entityDao.get(TCmsCategory.class, "o.code=?1", new Object[]{categoryCode});
                if (null != category) {
                    tmpTZoneCollect.setCategoryPoster(category.getPoster());
                }
                entityDao.update(tmpTZoneCollect);
                resultDesc = resultDesc + "更新成功！";
                logger.error(resultDesc);
                return resp;
            }
            LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
            orderBy.put("recordTime", "desc");
            List<TZoneCollect> tmpListTZoneCollect = entityDao.getScrollData(TZoneCollect.class, -1, -1, "o.tzone.code=?1 and o.userId=?2",
                    new Object[]{zoneCode, userID}, orderBy);
            if (tmpListTZoneCollect != null && !tmpListTZoneCollect.isEmpty()) {
                int tmpSize = tmpListTZoneCollect.size();
                if (tmpCollectLimit <= tmpSize) {
                	logger.info("收藏已达上限，删除一些,上限["+tmpCollectLimit+"],已有数量["+tmpSize+"]");
                    for (int i = tmpCollectLimit - 1; i < tmpSize; i++) {
                        entityDao.deleteDetached(tmpListTZoneCollect.get(i));
                    }
                }
            }
            tmpTZoneCollect = new TZoneCollect();
            tmpTZoneCollect.setCpCode(tmpTZone.getCpCode());
            tmpTZoneCollect.setProgramCode(programCode);
            tmpTZoneCollect.setProgramName(programName);
            tmpTZoneCollect.setRecordTime(new Date());
            tmpTZoneCollect.setSeriesFlag(seriesFlag);
            tmpTZoneCollect.setSeriesCode(seriesCode);
            tmpTZoneCollect.setTzone(tmpTZone);
            tmpTZoneCollect.setUserId(userID);
            tmpTZoneCollect.setPosterUrl(poster);

            if (seriesFlag == 1) {
                TCmsSeries tcmsSeries = entityDao.get(TCmsSeries.class, "o.code=?1", new Object[]{seriesCode});
                if (null != tcmsSeries) {
                    tmpTZoneCollect.setStillImg(tcmsSeries.getStillUrl());
                }
            } else if (seriesFlag == 0) {
                TCmsProgram tmpTProgram = entityDao.get(TCmsProgram.class, "o.code=?1", new Object[]{programCode});
                if (null != tmpTProgram) {
                    tmpTZoneCollect.setStillImg(tmpTProgram.getStillUrl());
                }
            }
            TCmsCategory category = entityDao.get(TCmsCategory.class, "o.code=?1", new Object[]{categoryCode});
            if (null != category) {
                tmpTZoneCollect.setCategoryPoster(category.getPoster());
            }

            entityDao.saveObj(tmpTZoneCollect);
            resultDesc = resultDesc + "成功！";
            logger.info(resultDesc);
        } catch (Exception e) {
            resultDesc = resultDesc + "失败，程序异常！";
            logger.error(resultDesc, e);
            resp.setResultCode(ZoneManagerResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc);
        }
        return resp;
    }

    @Transactional
    public RemoveZoneCollectResp removeCollect(String zoneCode, String userID, String programCode) {
        RemoveZoneCollectResp resp = new RemoveZoneCollectResp();
        String resultDesc = String.format("用户[%s]取消专区[%s]收藏[%s]", userID, zoneCode, programCode);
        try {
            if (StringUtils.isEmpty(StringUtils.trim(zoneCode)) || StringUtils.isEmpty(StringUtils.trim(userID))
                    || StringUtils.isEmpty(StringUtils.trim(programCode))) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            TZoneCollect tmpTZoneCollect = entityDao.get(TZoneCollect.class, "o.tzone.code=?1 and o.userId=?2 and o.programCode=?3",
                    new Object[]{zoneCode, userID, programCode});
            if (tmpTZoneCollect == null) {
                resultDesc = resultDesc + "失败，内容未加入收藏！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.CONTENT_IS_NOT_COLLECTE);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            entityDao.deleteDetached(tmpTZoneCollect);
            resultDesc = resultDesc + "成功！";
            logger.info(resultDesc);
        } catch (Exception e) {
            resultDesc = resultDesc + "失败，程序异常！";
            logger.error(resultDesc, e);
            resp.setResultCode(ZoneManagerResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc);
        }
        return resp;

    }

    public GetZoneCollectResp getCollect(String zoneCode, String userID, String programCode) {
        GetZoneCollectResp resp = new GetZoneCollectResp();
        String resultDesc = String.format("用户[%s]获取专区[%s]收藏[%s]", userID, zoneCode, programCode);
        try {
            if (StringUtils.isEmpty(StringUtils.trim(zoneCode)) || StringUtils.isEmpty(StringUtils.trim(userID))
                    || StringUtils.isEmpty(StringUtils.trim(programCode))) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            TZoneCollect tmpTZoneCollect = entityDao.get(TZoneCollect.class, "o.tzone.code=?1 and o.userId=?2 and o.programCode=?3",
                    new Object[]{zoneCode, userID, programCode});
            if (tmpTZoneCollect == null) {
                resultDesc = resultDesc + "失败，内容未加入收藏！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.CONTENT_IS_NOT_COLLECTE);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            resp.setImgAddress(config.getImgAddress());
            resp.setCpCode(tmpTZoneCollect.getCpCode());
            resp.setProgramCode(programCode);
            resp.setProgramName(tmpTZoneCollect.getProgramName());
            resp.setRecordTime(DateFormatUtil.format(tmpTZoneCollect.getRecordTime(), "yyyy-MM-dd HH:mm:ss"));
            resp.setSeriesFlag(tmpTZoneCollect.getSeriesFlag());
            resp.setCategoryPoster(tmpTZoneCollect.getCategoryPoster());
            resp.setStillImg(tmpTZoneCollect.getStillImg());
            resp.setUserID(userID);
            resp.setZoneCode(zoneCode);
            resp.setSeriesCode(tmpTZoneCollect.getSeriesCode());
            resp.setPoster(tmpTZoneCollect.getPosterUrl());

            resultDesc = resultDesc + "成功！";
            logger.info(resultDesc);
        } catch (Exception e) {
            resultDesc = resultDesc + "失败，程序异常！";
            logger.error(resultDesc, e);
            resp.setResultCode(ZoneManagerResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc);
        }
        return resp;

    }

    public GetZoneCollectListResp getCollectList(String zoneCode, String userID, int firstIndex, int maxResult) {
        GetZoneCollectListResp resp = new GetZoneCollectListResp();
        String resultDesc = String.format("用户[%s]获取专区[%s]收藏列表", userID, zoneCode);
        try {
            if (StringUtils.isEmpty(StringUtils.trim(zoneCode)) || StringUtils.isEmpty(StringUtils.trim(userID))) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            String tmpCountHql = "select count(o.id) as count from TZoneCollect o where o.tzone.code=? and o.userId=?";
            //tmpCountHql += " and exists (select 1 from TCmsProgram t where t.code=o.programCode and t.status=1)";
            List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql, new Object[]{zoneCode, userID}, -1, -1);
            int tmpIntCount = 0;
            if (tmpListMapCount != null && !tmpListMapCount.isEmpty()) {
                Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
                Long tmpLongCount = (Long) tmpMapCount.get("count");
                tmpIntCount = tmpLongCount.intValue();
            }
            if (tmpIntCount <= 0) {
                return resp;
            }

            LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
            orderBy.put("recordTime", "desc");
            List<TZoneCollect> tmpListTZoneCollect = entityDao.getScrollData(TZoneCollect.class, firstIndex, maxResult,
                    //"o.tzone.code=?1 and o.userId=?2 and exists (select 1 from TCmsProgram t where t.code=o.programCode and t.status=1)", new Object[]{zoneCode, userID}, orderBy);
                    "o.tzone.code=?1 and o.userId=?2 ", new Object[]{zoneCode, userID}, orderBy);
            if (tmpListTZoneCollect == null || tmpListTZoneCollect.isEmpty()) {
                return resp;
            }
            List<GetZoneCollectListResp.ZoneCollectInfo> tmpListZoneCollectInfo = new ArrayList<GetZoneCollectListResp.ZoneCollectInfo>();
            GetZoneCollectListResp.ZoneCollectInfo tmpZoneCollectInfo;
            for (TZoneCollect tmpTZoneCollect : tmpListTZoneCollect) {
                tmpZoneCollectInfo = new GetZoneCollectListResp.ZoneCollectInfo();
                tmpZoneCollectInfo.setCpCode(tmpTZoneCollect.getCpCode());
                tmpZoneCollectInfo.setProgramCode(tmpTZoneCollect.getProgramCode());
                tmpZoneCollectInfo.setProgramName(tmpTZoneCollect.getProgramName());
                tmpZoneCollectInfo.setRecordTime(DateFormatUtil.format(tmpTZoneCollect.getRecordTime(), "yyyy-MM-dd HH:mm:ss"));
                tmpZoneCollectInfo.setSeriesFlag(tmpTZoneCollect.getSeriesFlag());
                tmpZoneCollectInfo.setUserID(userID);
                tmpZoneCollectInfo.setZoneCode(zoneCode);
                tmpZoneCollectInfo.setSeriesCode(tmpTZoneCollect.getSeriesCode());
                tmpZoneCollectInfo.setPoster(tmpTZoneCollect.getPosterUrl());
                tmpZoneCollectInfo.setCategoryPoster(tmpTZoneCollect.getCategoryPoster());
                tmpZoneCollectInfo.setStillImg(tmpTZoneCollect.getStillImg());
                tmpZoneCollectInfo.setImgAddress(config.getImgAddress());
                tmpListZoneCollectInfo.add(tmpZoneCollectInfo);
            }
            resp.setZoneCollectInfos(tmpListZoneCollectInfo);
            resp.setRecordSize(tmpIntCount);
            resultDesc = resultDesc + "成功！";
            logger.info(resultDesc);
        } catch (Exception e) {
            resultDesc = resultDesc + "失败，程序异常！";
            logger.error(resultDesc, e);
            resp.setResultCode(ZoneManagerResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc);
        }
        return resp;

    }

    /**
     * 清空用户专区收藏列表
     *
     * @param zoneCode
     * @param userID
     * @return
     */
    @Transactional
    public RemoveZoneCollectResp emptyCollect(String zoneCode, String userID) {
        RemoveZoneCollectResp resp = new RemoveZoneCollectResp();
        String resultDesc = String.format("用户[%s]清空专区[%s]收藏列表", userID, zoneCode);
        try {
            if (StringUtils.isEmpty(StringUtils.trim(zoneCode)) || StringUtils.isEmpty(StringUtils.trim(userID))) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }

            String sql = "delete from t_zone_collect where USER_ID = '" + userID + "'";

            operateBySql(sql);

            resultDesc = resultDesc + "成功！";
            logger.info(resultDesc);
        } catch (Exception e) {
            resultDesc = resultDesc + "失败，程序异常！";
            logger.error(resultDesc, e);
            resp.setResultCode(ZoneManagerResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc);
        }
        return resp;

    }

    @Transactional
    public AddZonePlayRecordResp addPlayRecord(AddPlayRecordReq addPlayRecordReq) {
        AddZonePlayRecordResp resp = new AddZonePlayRecordResp();
        String resultDesc = "用户新增播放记录";
        try {
            if (addPlayRecordReq == null) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            String zoneCode = addPlayRecordReq.getZoneCode();
            String userID = addPlayRecordReq.getUserID();
            String programCode = addPlayRecordReq.getProgramCode();
            String programName = addPlayRecordReq.getProgramName();
            String categoryCode = addPlayRecordReq.getCategoryCode();
            int seriesFlag = addPlayRecordReq.getSeriesFlag();
            String seriesCode = addPlayRecordReq.getSeriesCode();
            int playTime = addPlayRecordReq.getPlayTime();
            int setNo = addPlayRecordReq.getSetNo();
            String poster = addPlayRecordReq.getPoster();
            int totalPlayTime = addPlayRecordReq.getTotalPlayTime();
            resultDesc = String.format("用户[%s]新增专区[%s]播放记录[%s|%s|%s]类型[%s]集号[%s]",
                    userID, zoneCode, programCode, programName, playTime, seriesFlag, setNo);

            if (StringUtils.isEmpty(StringUtils.trim(zoneCode)) || StringUtils.isEmpty(StringUtils.trim(userID))
                    || StringUtils.isEmpty(StringUtils.trim(programCode)) || StringUtils.isEmpty(StringUtils.trim(programName))) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            if (seriesFlag != 0 && seriesFlag != 1) {
                resultDesc = resultDesc + "失败，类型非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }

            if (playTime <= 0) {
                resultDesc = resultDesc + "失败，播放时长无效！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }

            TZone tmpTZone = entityDao.get(TZone.class, "o.code=?1", new Object[]{zoneCode});
            if (tmpTZone == null) {
                resultDesc = resultDesc + "失败，专区不存在，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            if (tmpTZone.getStatus() == 0) {
                resultDesc = resultDesc + "失败，专区已停用！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.ZONEHAS_BEEN_STOPPED);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            int tmpPlayRecordLimit = tmpTZone.getPlayRecordLimit() == null ? 0 : tmpTZone.getPlayRecordLimit();
            if (tmpPlayRecordLimit <= 0) {
                resultDesc = resultDesc + "失败，数据库数据错误！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.DATABASE_EXCEPTION);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            int tmpPlayTimeLimit = tmpTZone.getPlayTimeLimit() == null ? 0 : tmpTZone.getPlayTimeLimit();
            if (tmpPlayTimeLimit > 0 && tmpPlayTimeLimit > playTime) {
                resultDesc = String.format(resultDesc + "失败，播放时长[%s]不足[%s]，不作记录！", playTime, tmpPlayTimeLimit);
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            TZonePlay tmpTZonePlay = entityDao.get(TZonePlay.class, "o.tzone.code=?1 and o.userId=?2 and o.programCode=?3",
                    new Object[]{zoneCode, userID, programCode});
            if (tmpTZonePlay != null) {
                tmpTZonePlay.setPlayTime(playTime);
                tmpTZonePlay.setRecordTime(new Date());
                tmpTZonePlay.setProgramName(programName);
                tmpTZonePlay.setSeriesFlag(seriesFlag);
                tmpTZonePlay.setSetNo(setNo);
                tmpTZonePlay.setCpCode(tmpTZone.getCpCode());
                tmpTZonePlay.setSeriesCode(seriesCode);
                tmpTZonePlay.setPosterUrl(poster);
                tmpTZonePlay.setTotalPlayTime(totalPlayTime);
                if (seriesFlag == 1) {
                    TCmsSeries tcmsSeries = entityDao.get(TCmsSeries.class, "o.code=?1", new Object[]{seriesCode});
                    if (null != tcmsSeries) {
                        tmpTZonePlay.setStillImg(tcmsSeries.getStillUrl());
                    }
                } else if (seriesFlag == 0) {
                    TCmsProgram tmpTProgram = entityDao.get(TCmsProgram.class, "o.code=?1", new Object[]{programCode});
                    if (null != tmpTProgram) {
                        tmpTZonePlay.setStillImg(tmpTProgram.getStillUrl());
                    }
                }
                TCmsCategory category = entityDao.get(TCmsCategory.class, "o.code=?1", new Object[]{categoryCode});
                if (null != category) {
                    tmpTZonePlay.setCategoryPoster(category.getPoster());
                }
                entityDao.update(tmpTZonePlay);
                resultDesc = resultDesc + "更新成功！";
                logger.info(resultDesc);
                return resp;
            }
            LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
            orderBy.put("recordTime", "desc");
            List<TZonePlay> tmpListTZonePlay = entityDao.getScrollData(TZonePlay.class, -1, -1, "o.tzone.code=?1 and o.userId=?2",
                    new Object[]{zoneCode, userID}, orderBy);
            if (tmpListTZonePlay != null && !tmpListTZonePlay.isEmpty()) {
                int tmpSize = tmpListTZonePlay.size();
                if (tmpPlayRecordLimit <= tmpSize) {
                    for (int i = tmpPlayRecordLimit - 1; i < tmpSize; i++) {
                        entityDao.deleteDetached(tmpListTZonePlay.get(i));
                    }
                }
            }
            tmpTZonePlay = new TZonePlay();
            tmpTZonePlay.setCpCode(tmpTZone.getCpCode());
            tmpTZonePlay.setProgramCode(programCode);
            tmpTZonePlay.setProgramName(programName);
            tmpTZonePlay.setRecordTime(new Date());
            tmpTZonePlay.setSeriesFlag(seriesFlag);
            tmpTZonePlay.setSeriesCode(seriesCode);
            tmpTZonePlay.setTzone(tmpTZone);
            tmpTZonePlay.setUserId(userID);
            tmpTZonePlay.setPlayTime(playTime);
            tmpTZonePlay.setSetNo(setNo);
            tmpTZonePlay.setPosterUrl(poster);
            tmpTZonePlay.setTotalPlayTime(totalPlayTime);

            if (seriesFlag == 1) {
                TCmsSeries tcmsSeries = entityDao.get(TCmsSeries.class, "o.code=?1", new Object[]{seriesCode});
                if (null != tcmsSeries) {
                    tmpTZonePlay.setStillImg(tcmsSeries.getStillUrl());
                }
            } else if (seriesFlag == 0) {
                TCmsProgram tmpTProgram = entityDao.get(TCmsProgram.class, "o.code=?1", new Object[]{programCode});
                if (null != tmpTProgram) {
                    tmpTZonePlay.setStillImg(tmpTProgram.getStillUrl());
                }
            }
            TCmsCategory category = entityDao.get(TCmsCategory.class, "o.code=?1", new Object[]{categoryCode});
            if (null != category) {
                tmpTZonePlay.setCategoryPoster(category.getPoster());
            }
            entityDao.saveObj(tmpTZonePlay);
            resultDesc = resultDesc + "成功！";
            logger.info(resultDesc);
        } catch (Exception e) {
            resultDesc = resultDesc + "失败，程序异常！";
            logger.error(resultDesc, e);
            resp.setResultCode(ZoneManagerResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc);
        }
        return resp;

    }

    /**
     * 清空点播记录
     *
     * @param zoneCode
     * @param userID
     * @return
     */
    @Transactional
    public RemoveZonePlayRecordResp emptyPlayRecord(String zoneCode, String userID) {
        RemoveZonePlayRecordResp resp = new RemoveZonePlayRecordResp();
        String resultDesc = String.format("用户[%s]清空专区[%s]播放记录", userID, zoneCode);
        try {
            if (StringUtils.isEmpty(StringUtils.trim(zoneCode)) || StringUtils.isEmpty(StringUtils.trim(userID))) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            String sql = "delete from t_zone_play where USER_ID='" + userID + "'";

            operateBySql(sql);

            resultDesc = resultDesc + "成功！";
            logger.info(resultDesc);
        } catch (Exception e) {
            resultDesc = resultDesc + "失败，程序异常！";
            logger.error(resultDesc, e);
            resp.setResultCode(ZoneManagerResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc);
        }
        return resp;

    }

    @Transactional
    public RemoveZonePlayRecordResp removePlayRecord(String zoneCode, String userID, String programCode) {
        RemoveZonePlayRecordResp resp = new RemoveZonePlayRecordResp();
        String resultDesc = String.format("用户[%s]取消专区[%s]播放记录[%s]", userID, zoneCode, programCode);
        try {
            if (StringUtils.isEmpty(StringUtils.trim(zoneCode)) || StringUtils.isEmpty(StringUtils.trim(userID))
                    || StringUtils.isEmpty(StringUtils.trim(programCode))) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            TZonePlay tmpTZonePlay = entityDao.get(TZonePlay.class, "o.tzone.code=?1 and o.userId=?2 and o.programCode=?3",
                    new Object[]{zoneCode, userID, programCode});
            if (tmpTZonePlay == null) {
                resultDesc = resultDesc + "失败，内容未加入播放记录！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.CONTENT_IS_NOT_PLAYRECORD);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            entityDao.deleteDetached(tmpTZonePlay);
            resultDesc = resultDesc + "成功！";
            logger.info(resultDesc);
        } catch (Exception e) {
            resultDesc = resultDesc + "失败，程序异常！";
            logger.error(resultDesc, e);
            resp.setResultCode(ZoneManagerResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc);
        }
        return resp;

    }

    public GetZonePlayRecordResp getPlayRecord(String zoneCode, String userID, String programCode) {
        GetZonePlayRecordResp resp = new GetZonePlayRecordResp();
        String resultDesc = String.format("用户[%s]获取专区[%s]播放记录[%s]", userID, zoneCode, programCode);
        try {
            if (StringUtils.isEmpty(StringUtils.trim(zoneCode)) || StringUtils.isEmpty(StringUtils.trim(userID))
                    || StringUtils.isEmpty(StringUtils.trim(programCode))) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            TZonePlay tmpTZonePlay = entityDao.get(TZonePlay.class, "o.tzone.code=?1 and o.userId=?2 and o.programCode=?3",
                    new Object[]{zoneCode, userID, programCode});
            if (tmpTZonePlay == null) {
                resultDesc = resultDesc + "失败，内容未加入播放记录！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.CONTENT_IS_NOT_PLAYRECORD);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            resp.setImgAddress(config.getImgAddress());
            resp.setCpCode(tmpTZonePlay.getCpCode());
            resp.setProgramCode(programCode);
            resp.setProgramName(tmpTZonePlay.getProgramName());
            resp.setRecordTime(DateFormatUtil.format(tmpTZonePlay.getRecordTime(), "yyyy-MM-dd HH:mm:ss"));
            resp.setSeriesFlag(tmpTZonePlay.getSeriesFlag());
            resp.setUserID(userID);
            resp.setZoneCode(zoneCode);
            resp.setPlayTime(tmpTZonePlay.getPlayTime());
            resp.setSetNo(tmpTZonePlay.getSetNo());
            resp.setSeriesCode(tmpTZonePlay.getSeriesCode());
            resp.setPoster(tmpTZonePlay.getPosterUrl());
            resp.setCategoryPoster(tmpTZonePlay.getCategoryPoster());
            resp.setStillImg(tmpTZonePlay.getStillImg());
            resp.setTotalPlayTime(tmpTZonePlay.getTotalPlayTime());
            resultDesc = resultDesc + "成功！";
            logger.info(resultDesc);
        } catch (Exception e) {
            resultDesc = resultDesc + "失败，程序异常！";
            logger.error(resultDesc, e);
            resp.setResultCode(ZoneManagerResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc);
        }
        return resp;

    }

    public GetZonePlayRecordListResp getPlayRecordList(String zoneCode, String userID, int firstIndex, int maxResult) {
        GetZonePlayRecordListResp resp = new GetZonePlayRecordListResp();
        String resultDesc = String.format("用户[%s]获取专区[%s]播放记录列表", userID, zoneCode);
        try {
            if (StringUtils.isEmpty(StringUtils.trim(zoneCode)) || StringUtils.isEmpty(StringUtils.trim(userID))) {
                resultDesc = resultDesc + "失败，参数非法！";
                logger.error(resultDesc);
                resp.setResultCode(ZoneManagerResultCode.PARAMETER_IS_NOT_LEGAL);
                resp.setResultDesc(resultDesc);
                return resp;
            }
            String tmpCountHql = "select count(o.id) as count from TZonePlay o where o.tzone.code=? and o.userId=?";
            //tmpCountHql += " and exists (select 1 from TCmsProgram t where t.code=o.programCode and t.status=1)";
            List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql, new Object[]{zoneCode, userID}, -1, -1);
            int tmpIntCount = 0;
            if (tmpListMapCount != null && !tmpListMapCount.isEmpty()) {
                Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
                Long tmpLongCount = (Long) tmpMapCount.get("count");
                tmpIntCount = tmpLongCount.intValue();
            }
            if (tmpIntCount <= 0) {
                return resp;
            }

            LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
            orderBy.put("recordTime", "desc");
            List<TZonePlay> tmpListTZonePlay = entityDao.getScrollData(TZonePlay.class, firstIndex, maxResult,
                    //"o.tzone.code=?1 and o.userId=?2 and exists (select 1 from TCmsProgram t where t.code=o.programCode and t.status=1)", new Object[]{zoneCode, userID}, orderBy);
                    "o.tzone.code=?1 and o.userId=?2 ", new Object[]{zoneCode, userID}, orderBy);
            if (tmpListTZonePlay == null || tmpListTZonePlay.isEmpty()) {
                return resp;
            }
            List<GetZonePlayRecordListResp.ZonePlayRecordInfo> tmpListZonePlayRecordInfo = new ArrayList<GetZonePlayRecordListResp.ZonePlayRecordInfo>();
            GetZonePlayRecordListResp.ZonePlayRecordInfo tmpZonePlayRecordInfo;
            for (TZonePlay tmpTZonePlay : tmpListTZonePlay) {
                tmpZonePlayRecordInfo = new GetZonePlayRecordListResp.ZonePlayRecordInfo();
                tmpZonePlayRecordInfo.setCpCode(tmpTZonePlay.getCpCode());
                tmpZonePlayRecordInfo.setProgramCode(tmpTZonePlay.getProgramCode());
                tmpZonePlayRecordInfo.setProgramName(tmpTZonePlay.getProgramName());
                tmpZonePlayRecordInfo.setRecordTime(DateFormatUtil.format(tmpTZonePlay.getRecordTime(), "yyyy-MM-dd HH:mm:ss"));
                tmpZonePlayRecordInfo.setSeriesFlag(tmpTZonePlay.getSeriesFlag());
                tmpZonePlayRecordInfo.setUserID(userID);
                tmpZonePlayRecordInfo.setZoneCode(zoneCode);
                tmpZonePlayRecordInfo.setPlayTime(tmpTZonePlay.getPlayTime());
                tmpZonePlayRecordInfo.setSetNo(tmpTZonePlay.getSetNo());
                tmpZonePlayRecordInfo.setSeriesCode(tmpTZonePlay.getSeriesCode());
                tmpZonePlayRecordInfo.setPoster(tmpTZonePlay.getPosterUrl());
                tmpZonePlayRecordInfo.setTotalPlayTime(tmpTZonePlay.getTotalPlayTime());
                tmpZonePlayRecordInfo.setImgAddress(config.getImgAddress());
                tmpZonePlayRecordInfo.setCategoryPoster(tmpTZonePlay.getCategoryPoster());
                tmpZonePlayRecordInfo.setStillImg(tmpTZonePlay.getStillImg());
                tmpListZonePlayRecordInfo.add(tmpZonePlayRecordInfo);
            }
            resp.setZonePlayRecordInfos(tmpListZonePlayRecordInfo);
            resp.setRecordSize(tmpIntCount);
            resultDesc = resultDesc + "成功！";
            logger.info(resultDesc);
        } catch (Exception e) {
            resultDesc = resultDesc + "失败，程序异常！";
            logger.error(resultDesc, e);
            resp.setResultCode(ZoneManagerResultCode.APPLICATION_EXCEPTION);
            resp.setResultDesc(resultDesc);
        }
        return resp;
    }
}

